package com.media.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;
import com.media.mapper.MediaProcessMapper;
import com.media.po.MediaFiles;
import com.media.po.MediaProcess;
import com.media.po.MediaProcessHistory;
import com.media.service.MediaFilesService;
import com.media.service.MediaProcessHistoryService;
import com.media.service.MediaProcessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ling
 */
@Slf4j
@Service
public class MediaProcessServiceImpl extends ServiceImpl<MediaProcessMapper, MediaProcess> implements MediaProcessService {

    @Autowired
    private MediaProcessMapper mediaProcessMapper;

    @Autowired
    private MediaProcessHistoryService mediaProcessHistoryService;

    @Autowired
    private MediaFilesService mediaFilesService;
    /**
     * 添加待处理任务至process表中
     *
     * @param mediaFiles
     */
    @Override
    public void addTask(MediaFiles mediaFiles) {
        //文件名称
        String filename = mediaFiles.getFilename();
        //文件扩展名
        String extension = filename.substring(filename.lastIndexOf("."));
        //文件mimeType
        String mimeType = getMimeType(extension);
        //如果是avi视频添加到视频待处理表
        if (mimeType.equals("video/x-msvideo")) {
            MediaProcess mediaProcess = new MediaProcess();
            BeanUtils.copyProperties(mediaFiles, mediaProcess);
            mediaProcess.setStatus("1");//未处理
            mediaProcess.setFailCount(0);//失败次数默认为0
            mediaProcessMapper.insert(mediaProcess);
        }
    }

    //根据扩展名获取mimeType
    private String getMimeType(String extension) {
        if (extension == null)
            extension = "";
        //根据扩展名取出mimeType
        ContentInfo extensionMatch = ContentInfoUtil.findExtensionMatch(extension);
        //通用mimeType，字节流
        String mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        if (extensionMatch != null) {
            mimeType = extensionMatch.getMimeType();
        }
        return mimeType;
    }

    /**
     * 获取任务列表
     *
     * @param shardIndex
     * @param shardTotal
     * @param count
     * @return
     */
    @Override
    public List<MediaProcess> getWaitingTask(int shardIndex, int shardTotal, int count) {
        //获取需要转码的任务
        return mediaProcessMapper.selectTranscodingList(shardIndex, shardTotal, count);
    }

    /**
     * 开始一个任务，设置状态为4,避免重复取到这个任务（分布式锁）
     *
     * @param taskId
     * @return
     */
    @Override
    public boolean startTask(long taskId) {
        int i = mediaProcessMapper.startTask(taskId);
        return i > 0;
    }

    /**
     * 保存任务处理结果
     *
     * @param taskId
     * @param status
     * @param fileId
     * @param url
     * @param errorMsg
     */
    @Override
    public void saveProcessFinishStatus(Long taskId, String status, String fileId, String url, String errorMsg) {
        MediaProcess mediaProcess = mediaProcessMapper.selectById(taskId);
        if (mediaProcess == null) {
            return;
        }

        //任务处理失败
        if ("3".equals(status)) {
            mediaProcess.setStatus("3");
            mediaProcess.setErrormsg(errorMsg);
            mediaProcessMapper.updateById(mediaProcess);

            log.error("更新任务处理失败记录，失败原因：{}", errorMsg);
            return;
        }

        //任务执行成功更新视频的URL、及任务处理结果，将待处理任务记录删除，同时向历史任务表添加记录
        MediaFiles mediaFiles = mediaFilesService.getById(fileId);

        //更新媒资信息
        mediaFiles.setUrl(url);
        mediaFilesService.updateById(mediaFiles);

        //更新任务处理结果
        mediaProcess.setStatus("2");
        mediaProcess.setUrl(url);
        mediaProcess.setFinishDate(LocalDateTime.now());
        mediaProcess.setErrormsg(errorMsg);
        mediaProcessMapper.updateById(mediaProcess);

        //添加至任务处理结果历史表中
        MediaProcessHistory mediaProcessHistory = new MediaProcessHistory();
        BeanUtils.copyProperties(mediaProcess, mediaProcessHistory);
        mediaProcessHistoryService.save(mediaProcessHistory);

        //删除任务处理结果表中的数据
        mediaProcessMapper.deleteById(taskId);
    }
}
